package com.fable.common.utils;


import io.jsonwebtoken.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data
@Component
@Slf4j
//@ConfigurationProperties(prefix = "gzh.jwt")
public class JwtUtils {

    @Value("${jwt.expiration}")
    private long expire;

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.tokenHeader}")
    private String header;

    // 生成jwt
    public String generateToken(String username) {

        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 10000 * expire);
//        Date expireDate = new Date(nowDate.getTime() + 36000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }


    /**
     * 解析token
     * @param token
     * */
    public Claims getClaimByToken(String token) throws ExpiredJwtException{
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从token中获取用户名
     */
    public String getUsername(String token) {
        try {
            return getClaimByToken(token).getSubject();
        } catch (ExpiredJwtException e) {
            return e.getClaims().getSubject();
        }

    }

    /**
     * 解析token是否过期 
     * @param claims
     * */
    public boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }
}
